package emp.servlet;

import emp.dao.UserDao;
import emp.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 叶枫
 * @date 2024/12/18.
 */

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserDao userDao;
    @Override
    public void init() throws ServletException {
        userDao = new UserDao();

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 显示注册页面
        request.getRequestDispatcher("/register.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单数据
        request.setCharacterEncoding("utf-8");//处理乱码
        String userName = request.getParameter("username");
        String passWord = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        String role = request.getParameter("role");
        User user = new User();
        user.setPassword(passWord);
        user.setUsername(userName);
        user.setRole(role);

        // 检查用户名是否已存在
        if (userDao.checkUserExists(userName)) {
            response.getWriter().write("<h3>Username already exists. Please choose another one.</h3>");
            return;
        }

        // 创建新用户

        boolean success = userDao.register(user);

        if (success) {
            response.getWriter().write("<h3>Registration successful! You can now <a href='login.jsp'>login</a>.</h3>");
        } else {
            response.getWriter().write("<h3>Registration failed. Please try again later.</h3>");
        }

    }
}
